package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.SyUserTaskInfoVo;
import com.eco.fanliapp.vo.SyUserTaskVo;
import com.github.pagehelper.PageHelper;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-08-07
 */
@Service
@Slf4j
public class SyUserTaskServiceImpl extends ServiceImpl<SyUserTaskMapper, SyUserTask> implements ISyUserTaskService {
    @Autowired
    private SyUserTaskMapper syUserTaskMapper;
    @Autowired
    private AppUserRedRewardMapper appUserRedRewardMapper;
    @Autowired
    private UpdateUserCommon updateUserCommon;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private ISySwitchService iSySwitchService;
    @Autowired
    private IAppUserRewardSetupService appUserRewardSetupService;
    @Autowired
    private RedisLockService redisLockService;
    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private SqjdAppUserMapper sqjdAppUserMapper;
    @Autowired
    private SqjdUserLogMapper sqjdUserLogMapper;
    @Autowired
    private ISyUserMoneyService syUserMoneyService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLISogService;
    @Autowired
    private IAppUserService appUserService;

    /**
     * 现金收入明细
     *
     * @return
     */
    @Override
    public ServerResponse cashIncomeDetails(Integer pageNum, Integer pageSize, Long userId) throws ParseException {
        pageSize = pageSize == null ? 20 : pageSize;
        pageNum = pageNum == null ? 1 : pageNum;
        PageHelper.startPage(pageNum, pageSize);
        List<SyUserTaskVo> syUserTask = syUserTaskMapper.cashIncomeDetails(userId);
        List<SyUserTaskInfoVo> syUserTaskvo = new ArrayList<>();
        if (syUserTask.size() != 0) {
            for (SyUserTaskVo task : syUserTask) {
                SyUserTaskInfoVo vo = new SyUserTaskInfoVo();
                vo.setUserId(task.getUserId());
                if (task.getTaskRewardMoney() == null || task.getTaskRewardMoney().compareTo(new BigDecimal(0)) == 0) {
                    vo.setTaskRewardMoney("+" + task.getExchangeCashAmount());
                } else {
                    if (task.getTaskRewardMoney().doubleValue() < 0) {
                        vo.setTaskRewardMoney(task.getTaskRewardMoney().toString());
                    } else {
                        vo.setTaskRewardMoney("+" + task.getTaskRewardMoney());
                    }
                }
                if (task.getCreateTime() != null) {
                    vo.setCreateTime(task.getCreateTime().getTime());
                }
                if (StringUtils.isNull(task.getTaskName())) {
                    vo.setTaskName("金币兑换成现金");
                } else {
                    vo.setTaskName(task.getTaskName());
                }
                syUserTaskvo.add(vo);
            }

            return ServerResponse.createBySuccess("现金收益明细获取成功", syUserTaskvo);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多数据");
        }
    }

    /**
     * 金币收益明细
     *
     * @return
     */
    @Override
    public ServerResponse goldIncomeDetails(Integer pageNum, Integer pageSize, Long userId) {
        pageSize = pageSize == null ? 20 : pageSize;
        pageNum = pageNum == null ? 0 : pageNum;

        PageHelper.startPage(pageNum, pageSize);
        //金币收入明细
        List<SyUserTaskVo> syGoldTask = syUserTaskMapper.goldIncomeDetails(userId);
        List<SyUserTaskInfoVo> syUserTaskvo = new ArrayList<>();
        if (syGoldTask.size() != 0) {
            for (SyUserTaskVo task : syGoldTask) {
                SyUserTaskInfoVo vo = new SyUserTaskInfoVo();
                vo.setUserId(task.getUserId());
                if (task.getTaskName().equals("1")) {
                    vo.setTaskName("金币兑换成现金");
                    vo.setTaskRewardNum("-" + task.getTaskRewardNum());
                    if (task.getExchangeCashAmount() != null) {
                        if (task.getExchangeCashAmount().compareTo(new BigDecimal(0)) == 0) {
                            vo.setExchangeCashAmount(null);
                        } else {
                            vo.setExchangeCashAmount("+" + task.getExchangeCashAmount());
                        }

                    }
                } else {
                    vo.setTaskName(task.getTaskName());
                    vo.setTaskRewardNum("+" + task.getTaskRewardNum());
                }
                if (task.getCreateTime() != null) {
                    vo.setCreateTime(task.getCreateTime().getTime());
                }
                syUserTaskvo.add(vo);
            }
            return ServerResponse.createBySuccess("金币收益明细获取成功", syUserTaskvo);
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "没有更多数据");
        }

    }

    /**
     * 插入任务日志
     *
     * @param syUserTask
     * @return
     */
    @Override
    public int insertsyUserTask(SyUserTask syUserTask) {
        return syUserTaskMapper.insert(syUserTask);
    }

    /**
     * 查询签到状态，是否签到
     *
     * @return
     */
    @Override
    public ServerResponse getSignStatus(Long userId) {
        List<SyUserTaskVo> syUserTask = syUserTaskMapper.selectUserTask(userId);
        if (syUserTask.size() > 0) {
            return ServerResponse.createBySuccess("已签到", 1);
        }
        return ServerResponse.createBySuccess("未签到", 0);
    }

    @Override
    public SyUserTask selectOne(QueryWrapper<SyUserTask> queryWrapper) {
        return syUserTaskMapper.selectOne(queryWrapper);
    }

    /**
     * 新手任务，复制链接--新
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse goodsCopyLink(Long userId) {
        HashMap map = new HashMap();

        AppUserRewardSetup appUserRewardSetup = null;
        if (redisTemplate.hasKey("AppUserRewardSetup")) {
            appUserRewardSetup = (AppUserRewardSetup) redisTemplate.opsForValue().get("AppUserRewardSetup");
        } else {
            appUserRewardSetup = appUserRewardSetupService.getById(1);
            redisTemplate.opsForValue().set("AppUserRewardSetup", appUserRewardSetup, 1, TimeUnit.HOURS);
        }
        //查询此红包是否存在
        AppUserRedReward redReward = appUserRedRewardMapper.getNewRedMoneyPacket(userId);
        if (redReward == null) {
            return ServerResponse.createByErrorMessage("红包失效或已领取");
        }
        //存redis
        Calendar cale = Calendar.getInstance();
        int hour = cale.get(Calendar.HOUR_OF_DAY);
        //先从缓存中搜索记录
        String redisKeyStr = "AppUserSearchHistory_" + hour;//当前小时
        if (redisTemplate.hasKey(redisKeyStr)) {
            Map<String, Set<String>> searchMap = (Map) redisTemplate.opsForValue().get(redisKeyStr);
            Set<String> userSet = searchMap.get(userId.toString());
            if (userSet != null && userSet.size() > 0) {
                log.info("用户复制链接任务完成{}", userId);
            } else {
                AppUserSearchHistory appUserSearchHistory = appUserRedRewardMapper.selectAppUserHistory(userId);
                if (appUserSearchHistory == null) {
                    return ServerResponse.createByErrorMessage("未完成复制链接任务");
                }
            }
        } else {
            AppUserSearchHistory appUserSearchHistory = appUserRedRewardMapper.selectAppUserHistory(userId);
            if (appUserSearchHistory == null) {
                return ServerResponse.createByErrorMessage("未完成复制链接任务");
            }
        }


        //新人更新红包状态
        AppUserRedReward redReward2 = new AppUserRedReward();
        redReward2.setTableId(redReward.getTableId());
        redReward2.setHbStatus(5);
        redReward2.setHbMoney(appUserRewardSetup.getNewRedMoneyFixation());
        redReward2.setUpdateTime(new Date().getTime());
        redReward2.setHandle(1);
        int i = appUserRedRewardMapper.updateHbMoneyStatus(redReward2);
        if (i > 0) {
            //获取用户信息
            AppUser appUser = appUserService.selectAppUserByUserId(userId,0);
            BigDecimal cashBalance = new BigDecimal(0);
            if (appUser != null) {
                cashBalance = appUser.getBalance();
            }
            //支付宝账户加钱
            int ii = updateUserCommon.updateUserBalanceMoney(appUserRewardSetup.getNewRedMoneyFixation(), redReward.getUserId(), 1);//新手任务2
            //账户金额发生变动，添加账户变更日志
            String remark = "新手任务，复制链接红包到账支付宝余额";
            Integer logStatus = 0;//加钱
            syUserMoneyLogService.addSyUserMoneyLog(userId, cashBalance, appUserRewardSetup.getNewRedMoneyFixation(), remark, null, logStatus);


            map.put("title", "复制链接查询奖励");
            map.put("moneyNum", appUserRewardSetup.getNewRedMoneyFixation());
            map.put("displayTime", ApiEnum.DIS_TIME);//弹窗显示时间毫秒
            return ServerResponse.createBySuccess("任务完成", map);

        } else {
            return ServerResponse.createByErrorMessage("红包状态更新失败");
        }

    }

    //省钱间谍加钱
    private void sqjdAddMoney(String phoneNumber) {
        List<String> sqjdPhones = new ArrayList<>();
        String str = "sqjd_all_phone_num===";
        if (redisTemplateService.hasKey(str)) {
            List tByKey = redisTemplateService.getTByKey(str, List.class);
            sqjdPhones.addAll(tByKey);
        }
        if (sqjdPhones.size() <= 0 || sqjdPhones == null) {
            List<String> strings = sqjdAppUserMapper.selectAllPhoneNum();
            sqjdPhones.addAll(strings);
            redisTemplateService.set(str, strings, 0L);
        }
        AppUser appUser1 = null;
        SqjdAppUser sqjdAppUser = null;
        for (String phoneNum : sqjdPhones) {
            if (phoneNum.equals(phoneNumber)) {
                appUser1 = appUserMapper.selectAppUserByAlipayPhoneNumber(phoneNumber);
                sqjdAppUser = sqjdAppUserMapper.selectUserByPhoneNum(phoneNumber);
                break;
            }
        }
        if (appUser1 != null && sqjdAppUser != null && sqjdAppUser.getDeleted() == 0) {
            BigDecimal commission = sqjdAppUser.getAmount();
            BigDecimal commission1 = sqjdAppUser.getTotal().divide(new BigDecimal(100));
            commission1.setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal add = commission.add(commission1);
            add.setScale(2, BigDecimal.ROUND_HALF_UP);
            try {
                syUserMoneyService.updateSqjd(appUser1, add, phoneNumber);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 新手任务，完善手机号--新
     *
     * @param userId
     * @return
     */
    @Override
    @Synchronized
    public ServerResponse perfectPohoneNumber(Long userId, String phoneNumber, String code) {
        HashMap map = new HashMap();
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 60;

        String verifyCode = (String) redisTemplate.opsForValue().get(phoneNumber);
        verifyCode = verifyCode == null ? "" : verifyCode;
        if (!verifyCode.equals(code)) {
            return ServerResponse.createByErrorMessage("验证码错误");
        } else {
            //获取锁
            if (!redisLockService.lock(userId + "perfectPohoneNumber" + phoneNumber, startTimes + "")) {
                return ServerResponse.createByErrorMessage("您操作太频繁了，3秒后再试吧");
            }

            //获取用户账户数据
            AppUser appUser = appUserMapper.selectAppUserByUserId(userId);
            //首次查询用户钱中是否存在数据
            SyUserMoney oldSyUserMoney = iSyUserMoneyService.selectByUserId(userId);
            BigDecimal cashBalanceAmount = new BigDecimal(0);
            BigDecimal amount = new BigDecimal(0.2);
            if (oldSyUserMoney != null) {
                cashBalanceAmount = oldSyUserMoney.getCashBalanceAmount();
            }

            if (org.apache.commons.lang3.StringUtils.isEmpty(appUser.getAlipayPhoneNumber())) {
                int i = appUserMapper.updateAlipayPhoneNumber(phoneNumber, userId);
                //账户金额发生变动，添加账户变更日志
                String remark = "账户绑定手机号";
                //加钱
                Integer logStatus = 0;

                if (i > 0) {
                    //省钱间谍
                    sqjdAddMoney(phoneNumber);
                    int ii = updateUserCommon.UpdateUserMoney(new BigDecimal(0.2), userId, 3);
                    if (ii > 0) {
                        syUserMoneyLogService.addSyUserMoneyLog(userId, cashBalanceAmount, amount, remark, null, logStatus);
                        map.put("title", "完善手机号奖励");
                        map.put("moneyNum", 0.2);
                        map.put("displayTime", ApiEnum.DIS_TIME);//弹窗显示时间2秒
                        map.put("popup", true);//true 弹窗
                        return ServerResponse.createBySuccess(200, "绑定成功", map);
                    } else {
                        return ServerResponse.createByErrorMessage("领取奖励失败");
                    }
                } else {
                    return ServerResponse.createByErrorMessage("绑定失败");
                }
            } else {
                //查询是否有完成日志记录
                QueryWrapper<SyUserTask> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", userId);
                queryWrapper.eq("task_type_id", 3);
                SyUserTask syUserTask = syUserTaskMapper.selectOne(queryWrapper);
                if (syUserTask == null) {
                    int i = appUserMapper.updateAlipayPhoneNumber(phoneNumber, userId);
                    //账户金额发生变动，添加账户变更日志
                    String remark = "账户绑定手机号";
                    Integer logStatus = 0;//加钱
                    if (i > 0) {
                        //省钱间谍
                        sqjdAddMoney(phoneNumber);
                        int ii = updateUserCommon.UpdateUserMoney(new BigDecimal(0.2), userId, 3);
                        syUserMoneyLogService.addSyUserMoneyLog(userId, cashBalanceAmount, amount, remark, null, logStatus);
                        map.put("title", "完善手机号奖励");
                        map.put("moneyNum", 0.2);
                        map.put("displayTime", ApiEnum.DIS_TIME);//弹窗显示时间2秒
                        map.put("popup", true);//true 弹窗
                        if (ii > 0) {
                            return ServerResponse.createBySuccess(200, "修改成功", map);
                        } else {
                            return ServerResponse.createByErrorMessage("领取奖励失败");
                        }
                    }
                    return ServerResponse.createByErrorMessage("修改失败");
                } else {
                    int ii = appUserMapper.updateAlipayPhoneNumber(phoneNumber, userId);
                    if (ii > 0) {
                        //省钱间谍
                        sqjdAddMoney(phoneNumber);
                        map.put("popup", false);//fals  没弹窗
                        return ServerResponse.createBySuccess(200, "修改成功", map);
                    }
                    return ServerResponse.createByErrorMessage("修改失败");
                }
            }


        }
    }

    /**
     * 获取新人任务复制链接弹窗
     *
     * @return
     */
    @Override
    public ServerResponse redPacketPopUp(Long userId) {
        HashMap map = new HashMap();
        Boolean onOff = false;
        Date date = new Date();
        long time = date.getTime();

        SySwitch sySwitchRedOnOff = iSySwitchService.getById(5);//6首购红包弹窗叉号开关
        if (sySwitchRedOnOff != null) {
            if (sySwitchRedOnOff.getState() == 1) {
                onOff = true;
            } else {
                onOff = false;
            }
        }

        //新人红包
        AppUserRedReward appUserRedReward = appUserRedRewardMapper.getNewRedPacket(userId, 1, time);

        if (appUserRedReward == null) {
            return ServerResponse.createByErrorMessage("红包已失效");
        } else {
            AppUserRewardSetup appUserRewardSetup = null;
            if (redisTemplate.hasKey("AppUserRewardSetup")) {
                appUserRewardSetup = (AppUserRewardSetup) redisTemplate.opsForValue().get("AppUserRewardSetup");
            } else {
                appUserRewardSetup = appUserRewardSetupService.getById(1);
                redisTemplate.opsForValue().set("AppUserRewardSetup", appUserRewardSetup, 1, TimeUnit.HOURS);
            }
            map.put("packetMoney", appUserRewardSetup.getNewRedMoneyFixation());
            map.put("onoff", onOff);
            return ServerResponse.createBySuccess("查询成功", map);
        }
    }

    /**
     * 获取首购任务弹窗
     *
     * @return
     */
    @Override
    public ServerResponse taskPacketPopUp(Long userId) {

        HashMap map = new HashMap();
        Boolean onOff = false;//默认

        SySwitch sySwitchTaskOnOff = iSySwitchService.getById(6);//6首购红包弹窗叉号开关
        if (sySwitchTaskOnOff != null) {
            if (sySwitchTaskOnOff.getState() == 1) {
                onOff = true;
            } else {
                onOff = false;
            }
        }

        Date date = new Date();
        long time = date.getTime();
        AppUserRedReward appUserRedReward = appUserRedRewardMapper.getNewRedPacket(userId, 3, time);
        if (appUserRedReward == null) {
            return ServerResponse.createByErrorMessage("红包已失效");
        } else {
            AppUserRewardSetup appUserRewardSetup = null;
            if (redisTemplate.hasKey("AppUserRewardSetup")) {
                appUserRewardSetup = (AppUserRewardSetup) redisTemplate.opsForValue().get("AppUserRewardSetup");
            } else {
                appUserRewardSetup = appUserRewardSetupService.getById(1);
                redisTemplate.opsForValue().set("AppUserRewardSetup", appUserRewardSetup, 1, TimeUnit.HOURS);
            }
            map.put("packetMoney", appUserRewardSetup.getTaskRedMoneyAmount());
            map.put("onoff", onOff);
            return ServerResponse.createBySuccess("查询成功", map);
        }

    }

    /**
     * 签到推送开启设置
     *
     * @param userId
     * @param signPush
     * @return
     */
    @Override
    public ServerResponse signRemind(Long userId, String signPush) {
        if (StringUtils.isNotNull(signPush)) {
            int i = appUserMapper.updateSignPushByUserId(userId, signPush);
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("设置成功");
            }
            return ServerResponse.createByErrorMessage("设置失败");
        } else {
            return ServerResponse.createBySuccessCodeMessage(401, "signPush不能为空");
        }
    }

    /**
     * 新手任务完成数量（0.36，首购）
     *
     * @param userId
     * @return
     */
    @Override
    public Integer taskFinishNumber(Long userId) {
        return syUserTaskMapper.taskFinishNumber(userId);
    }

    /**
     * 根据UserId 创建sy_user_money
     *
     * @return
     */
    @Override
    public ServerResponse selectUserIdCreateUserMonye() {
        List<Long> list = appUserMapper.selectUserIdCreateUserMonye();
        for (Long userId : list
                ) {
            int km = iSyUserMoneyService.createUserMoney(userId);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sqjdAddMoney() {

        try {
            List<SqjdAppUser> sqjdAppUser = sqjdAppUserMapper.selectUserMoneyByPhoneNum();
            //给用户blance加钱
            //增加用户余额日志
            if (sqjdAppUser.size() > 0) {
                for (SqjdAppUser sqjdAppUser1 : sqjdAppUser) {
                    //根据手机号获取用户信息
                    AppUser appUser = appUserService.selectAppUserByAlipayPhoneNumber(sqjdAppUser1.getPhoneNumber());
                    log.info("省钱间谍余额变化，转入省鸭{}" + appUser.getUserId());
                    int i1 = appUserMapper.updateAppUserSqjdbalance(appUser.getUserId(), sqjdAppUser1.getTotal());
                    if (i1 > 0) {
                        syUserMoneyLISogService.addSyUserMoneyLogNew2(appUser.getUserId(), appUser.getBalance(),
                                sqjdAppUser1.getTotal(), "省钱间谍1.15到2.21余额变化，转入省鸭+" + sqjdAppUser1.getTotal() + ",转入时间" + new Date(), 5);
                        log.info("省钱间谍1.15到2.21余额变化，转入省鸭{}" + appUser.getUserId());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void sqjdAddMoneyLog() {
        List<SqjdUserLog> sqjdUserLog = sqjdUserLogMapper.selectUserLog();
        if (sqjdUserLog.size() > 0) {
            for (SqjdUserLog UserLog : sqjdUserLog) {
                syUserMoneyLISogService.addSyUserMoneyLogNew2(UserLog.getUserId(), UserLog.getBalance(),
                        UserLog.getBalances(), "省钱间谍中存在余额，且已经注册过省鸭的用户，转入省鸭{}+" + UserLog.getBalances() + ",转入时间2019-12-25 00:00:00", 4);
                log.info("省钱间谍中存在余额，且已经注册过省鸭的用户，转入省鸭{}" + UserLog.getUserId());
            }
        }

    }
}
